﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.CardAcct.Interfaces;
using PARK.CardAcct.Entitys.Dto.employee;
using PARK.System.Interfaces.Permission;
using PARK.Common.Util;
using PARK.System.Entitys.Permission;
using System.Text;
using PARK.CardAcct.Entitys;
using Microsoft.AspNetCore.Http;
using PARK.Common.Configuration;
using PARK.Common.Model.NPOI;
using PARK.DataEncryption;
using PARK.System.Interfaces.Common;
using PARK.CardAcct.Entitys.Dto;
using PARK.System.Interfaces.System;
using JNPF.System.Entitys;
using System.IO;
using System.Text.RegularExpressions;
using KYSharp.SM;
using System.Data;
using PARK.Consumer.Entity;
using PARK.System.Entitys.System;
using PARK.ClayObject;
using PARK.BussinCache.Interfaces;
using Microsoft.AspNetCore.Authorization;

namespace PARK.CardAcct.Employee
{
    /// <summary>
    /// 人员管理服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Card", Name = "Employee", Order = 200)]
    [Route("api/card/[controller]")]
    public class EmployeeService : IEmployeeService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<EmployeeEntity> _baseEmployeeRepository;
        private readonly IBillRullService _billRuleService;
        private readonly IFileService _fileService;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly IOrganizeService _organizeService; // 机构表仓储
        private readonly IUniubiSdkRepository _uniubiSdkRepository;
        private readonly IParkCacheRepository _parkCacheRepository;

        /// <summary>
        /// 初始化一个<see cref="EmployeeService"/>类型的新实例
        /// </summary>
        public EmployeeService(
            ISqlSugarRepository<EmployeeEntity> baseEmployeeRepository,
            IBillRullService billRuleService,
            IFileService fileService,
            IUserManager userManager,
            IOrganizeService organizeService,
            IUniubiSdkRepository uniubiSdkRepository,
            IParkCacheRepository parkCacheRepository)
        {
            _baseEmployeeRepository = baseEmployeeRepository;
            _billRuleService = billRuleService;
            _fileService = fileService;
            _db = _baseEmployeeRepository.Context;
            _userManager = userManager;
            _organizeService = organizeService;
            _uniubiSdkRepository = uniubiSdkRepository;
            _parkCacheRepository = parkCacheRepository;
        }

        #region Get
        /// <summary>
        /// 获取人员管理
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == id);
            var output = entity.Adapt<EmployeeInfoOutput>();
            if (entity != null)
            {
                try
                {
                    if (!string.IsNullOrEmpty(entity.MobilePhoneSf) && entity.MobilePhoneSf.Length > 0)
                    {
                        //加密手机号
                        SM4Utils sm4 = new SM4Utils();
                        sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
                        sm4.hexString = false;
                        //解密
                        output.mobilePhone = sm4.Decrypt_ECB(entity.MobilePhoneSf);
                    }
                    else
                    {
                        output.mobilePhone = "";
                        output.mobilePhoneSf = "";
                    }
                }
                catch
                {
                    output.mobilePhone = "";
                    output.mobilePhoneSf = "";
                }
            }
            if (entity.AuthTsMenu == 1)
            {
                output.authMenu = true;
            }
            else
            {
                output.authMenu = false;
            }
            return output;
        }
        /// <summary>
        /// 根据消费卡号获取人员管理
        /// </summary>
        /// <param name="cardNo">参数</param>
        /// <returns></returns>
        [HttpGet("GetInfoByCardNo/{cardNo}")]
        public async Task<dynamic> GetInfoByCardNo(string cardNo)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.CardNo.Equals(cardNo) && p.CompanyId == userInfo.companyId);
                var output = entity.Adapt<EmployeeInfoOutput>();
                return output;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
		/// 获取人员（正常、禁用）管理列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] EmployeeListQuery input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "sortCode" : input.sidx;
                var organizeIds = new List<string>();
                if (!input.organizeId.IsNullOrEmpty())
                    organizeIds = await GetSubOrganizeIds(input.organizeId);
                if (input.departId == "96240625-934F-490B-8AA6-0BC775B18468")
                {
                    input.departId = null;
                }
                //有效期
                List<string> querydate = input.expiryEndDate != null ? input.expiryEndDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startate = querydate != null ? Ext.GetDateTime(querydate.First()) : null;
                DateTime? enddate = querydate != null ? Ext.GetDateTime(querydate.Last()) : null;
                var data = await _db.Queryable<EmployeeEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    .Where(u => u.DeleteMark == 0 && u.AccStatus != 2 && u.AccStatus != 3 && u.AccStatus != 4)
                    //组织机构
                    .WhereIF(organizeIds.Any(), u => organizeIds.Contains(SqlFunc.ToString(u.DepartId)))
                    //关键字查询
                    .WhereIF(!input.keyword.IsNullOrEmpty(), u => u.JobNum.Contains(input.keyword) || u.RealName.Contains(input.keyword) || u.MobilePhone.Contains(input.keyword) || u.CardNo.Contains(input.keyword))
                    //卡户状态
                    .WhereIF(!string.IsNullOrEmpty(input.accStatus), u => u.AccStatus.Equals(input.accStatus))
                    //认证状态
                    .WhereIF(!string.IsNullOrEmpty(input.isauth), u => u.Isauth.Equals(input.isauth))                    
                    //卡号查询
                    .WhereIF(!string.IsNullOrEmpty(input.cardNo), u => u.CardNo.Contains(input.cardNo) || u.CatCardNo.Contains(input.cardNo))
                    //部门
                    .WhereIF(!string.IsNullOrEmpty(input.departId), p => p.DepartId.Equals(input.departId))
                    //有效期
                    .WhereIF(querydate != null, u => u.ExpiryEndDate >= new DateTime(startate.ToDate().Year, startate.ToDate().Month, startate.ToDate().Day, 0, 0, 0))
                    .WhereIF(querydate != null, u => u.ExpiryEndDate <= new DateTime(enddate.ToDate().Year, enddate.ToDate().Month, enddate.ToDate().Day, 23, 59, 59))
                    //员工类型
                    .WhereIF(!string.IsNullOrEmpty(input.employeType), p => p.EmployeType.Equals(input.employeType))
                    //卡片类型
                    .WhereIF(!string.IsNullOrEmpty(input.cardTypeId), p => p.CardTypeId.Equals(input.cardTypeId))
                    //超期状态
                    .WhereIF(!string.IsNullOrEmpty(input.overdueStatus), u => u.OverdueStatus.Equals(input.overdueStatus))
                    .Select(it => new EmployeeListOutput
                    {
                        employeeId = it.EmployeeId,
                        jobNum = it.JobNum,
                        realName = it.RealName,
                        gender = it.Gender,
                        employeType = it.EmployeType,
                        departId = it.DepartId,
                        departName = it.DepartName,
                        headIcon = it.HeadIcon,
                        mobilePhone = it.MobilePhone,
                        isCard = it.IsCard,
                        cardNo = it.CardNo,
                        catCardNo = it.CatCardNo, //长安通卡号
                        expiryEndDate = it.ExpiryEndDate,
                        welfareBalance = it.WelfareBalance,
                        rechargeBalance = it.RechargeBalance,
                        accStatus = it.AccStatus,
                        isauth = it.Isauth,
                        description = it.Description,
                        CreatorTime = it.CreatorTime,
                        cardUID = it.CardUID,
                        cardTypeId = it.CardTypeId,
                        cardTypeName = it.CardTypeName,
                        overdueStatus =it.OverdueStatus,
                        eyejob = it.Eyejob,                 
                        uni_is = it.uni_is,
                        uni_admitGuid = it.uni_admitGuid,
                        uni_faceGuid=it.uni_faceGuid,
                        uni_faceurl= it.uni_faceurl,
                        sortCode = it.SortCode
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<EmployeeListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
        /// <summary>
		/// 获取人员（正常、禁用）管理列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("GetAllno4List")]
        public async Task<dynamic> GetAllno4List([FromQuery] EmployeeListQuery input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "sortCode" : input.sidx;
                var organizeIds = new List<string>();
                if (!input.organizeId.IsNullOrEmpty())
                    organizeIds = await GetSubOrganizeIds(input.organizeId);
                if (input.departId == "96240625-934F-490B-8AA6-0BC775B18468")
                {
                    input.departId = null;
                }
                //有效期
                List<string> querydate = input.expiryEndDate != null ? input.expiryEndDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startate = querydate != null ? Ext.GetDateTime(querydate.First()) : null;
                DateTime? enddate = querydate != null ? Ext.GetDateTime(querydate.Last()) : null;
                var data = await _db.Queryable<EmployeeEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    .Where(u => u.DeleteMark == 0 && u.AccStatus != 4)
                    //组织机构
                    .WhereIF(organizeIds.Any(), u => organizeIds.Contains(SqlFunc.ToString(u.DepartId)))
                    //关键字查询
                    .WhereIF(!input.keyword.IsNullOrEmpty(), u => u.JobNum.Contains(input.keyword) || u.RealName.Contains(input.keyword) || u.MobilePhone.Contains(input.keyword))
                    //卡户状态
                    .WhereIF(!string.IsNullOrEmpty(input.accStatus), u => u.AccStatus.Equals(input.accStatus))
                    //卡号查询
                    .WhereIF(!string.IsNullOrEmpty(input.cardNo), u => u.CardNo.Contains(input.cardNo) || u.CatCardNo.Contains(input.cardNo))
                    //部门
                    .WhereIF(!string.IsNullOrEmpty(input.departId), p => p.DepartId.Equals(input.departId))
                    //员工类型
                    .WhereIF(!string.IsNullOrEmpty(input.employeType), p => p.EmployeType.Equals(input.employeType))
                     //卡片类型
                     .WhereIF(!string.IsNullOrEmpty(input.cardTypeId), p => p.CardTypeId.Equals(input.cardTypeId))
                    //有效期
                    .WhereIF(querydate != null, u => u.ExpiryEndDate >= new DateTime(startate.ToDate().Year, startate.ToDate().Month, startate.ToDate().Day, 0, 0, 0))
                    .WhereIF(querydate != null, u => u.ExpiryEndDate <= new DateTime(enddate.ToDate().Year, enddate.ToDate().Month, enddate.ToDate().Day, 23, 59, 59))
                    .Select(it => new EmployeeListOutput
                    {
                        employeeId = it.EmployeeId,
                        jobNum = it.JobNum,
                        realName = it.RealName,
                        gender = it.Gender,
                        employeType = it.EmployeType,
                        departId = it.DepartId,
                        departName = it.DepartName,
                        headIcon = it.HeadIcon,
                        mobilePhone = it.MobilePhone,
                        isCard = it.IsCard,
                        cardNo = it.CardNo,
                        catCardNo = it.CatCardNo, //长安通卡号
                        expiryEndDate = it.ExpiryEndDate,
                        welfareBalance = it.WelfareBalance,
                        rechargeBalance = it.RechargeBalance,
                        accStatus = it.AccStatus,
                        description = it.Description,
                        CreatorTime = it.CreatorTime,
                        cardUID = it.CardUID,
                        cardTypeId = it.CardTypeId,
                        cardTypeName = it.CardTypeName,
                        uni_is = it.uni_is,
                        uni_admitGuid = it.uni_admitGuid,
                        uni_faceGuid = it.uni_faceGuid,
                        uni_faceurl = it.uni_faceurl,
                        sortCode = it.SortCode
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<EmployeeListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
        /// <summary>
		/// 获取人员(挂失、销户）管理列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("GetLossList")]
        public async Task<dynamic> GetLossList([FromQuery] EmployeeListQuery input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "sortCode" : input.sidx;
                var organizeIds = new List<string>();
                if (!input.organizeId.IsNullOrEmpty())
                    organizeIds = await GetSubOrganizeIds(input.organizeId);
                //挂失日期
                List<string> querlossDate = input.lossDate != null ? input.lossDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startlossDate = querlossDate != null ? Ext.GetDateTime(querlossDate.First()) : null;
                DateTime? endlossDate = querlossDate != null ? Ext.GetDateTime(querlossDate.Last()) : null;
                //销户日期
                List<string> queryCancelDate = input.cancelDate != null ? input.cancelDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startCancelDate = queryCancelDate != null ? Ext.GetDateTime(queryCancelDate.First()) : null;
                DateTime? endCancelDate = queryCancelDate != null ? Ext.GetDateTime(queryCancelDate.Last()) : null;
                var data = await _db.Queryable<EmployeeEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    .Where(u => u.AccStatus == 3)
                    //删除标记
                    .Where(u => u.DeleteMark == 0)
                    //组织机构
                    .WhereIF(organizeIds.Any(), u => organizeIds.Contains(SqlFunc.ToString(u.DepartId)))
                    //员工类型
                    .WhereIF(!string.IsNullOrEmpty(input.employeType), p => p.EmployeType.Equals(input.employeType))
                     //卡片类型
                     .WhereIF(!string.IsNullOrEmpty(input.cardTypeId), p => p.CardTypeId.Equals(input.cardTypeId))
                    //关键字查询
                    .WhereIF(!input.keyword.IsNullOrEmpty(), u => u.JobNum.Contains(input.keyword) || u.RealName.Contains(input.keyword) || u.MobilePhone.Contains(input.keyword))
                    //卡号查询
                    .WhereIF(!string.IsNullOrEmpty(input.cardNo), u => u.CardNo.Contains(input.cardNo) || u.CatCardNo.Contains(input.cardNo))
                    //挂失日期
                    .WhereIF(querlossDate != null, u => u.LossAccDate >= new DateTime(startlossDate.ToDate().Year, startlossDate.ToDate().Month, startlossDate.ToDate().Day, 0, 0, 0))
                    .WhereIF(querlossDate != null, u => u.LossAccDate <= new DateTime(endlossDate.ToDate().Year, endlossDate.ToDate().Month, endlossDate.ToDate().Day, 23, 59, 59))
                    //销户日期
                    .WhereIF(queryCancelDate != null, u => u.CancelAccDate >= new DateTime(startCancelDate.ToDate().Year, startCancelDate.ToDate().Month, startCancelDate.ToDate().Day, 0, 0, 0))
                    .WhereIF(queryCancelDate != null, u => u.CancelAccDate <= new DateTime(endCancelDate.ToDate().Year, endCancelDate.ToDate().Month, endCancelDate.ToDate().Day, 23, 59, 59))
                    .Select(it => new EmployeeListOutput
                    {
                        employeeId = it.EmployeeId,
                        jobNum = it.JobNum,
                        realName = it.RealName,
                        gender = it.Gender,
                        employeType = it.EmployeType,
                        departId = it.DepartId,
                        departName = it.DepartName,
                        headIcon = it.HeadIcon,
                        mobilePhone = it.MobilePhone,
                        isCard = it.IsCard,
                        cardNo = it.CardNo,
                        catCardNo = it.CatCardNo, //长安通卡号
                        expiryEndDate = it.ExpiryEndDate,
                        welfareBalance = it.WelfareBalance,
                        rechargeBalance = it.RechargeBalance,
                        accStatus = it.AccStatus,
                        description = it.Description,
                        LossAccDate = it.LossAccDate,
                        CancelAccDate = it.CancelAccDate,
                        CreatorTime = it.CreatorTime,
                        cardUID = it.CardUID,
                        cardTypeId = it.CardTypeId,
                        cardTypeName = it.CardTypeName,
                        uni_is = it.uni_is,
                        uni_admitGuid = it.uni_admitGuid,
                        uni_faceGuid = it.uni_faceGuid,
                        uni_faceurl = it.uni_faceurl,
                        sortCode = it.SortCode
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<EmployeeListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
        /// <summary>
        /// 获取人员(销户）管理列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("GetCancelList")]
        public async Task<dynamic> GetCancelList([FromQuery] EmployeeListQuery input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "sortCode" : input.sidx;
                var organizeIds = new List<string>();
                if (!input.organizeId.IsNullOrEmpty())
                    organizeIds = await GetSubOrganizeIds(input.organizeId);
                //挂失日期
                List<string> querlossDate = input.lossDate != null ? input.lossDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startlossDate = querlossDate != null ? Ext.GetDateTime(querlossDate.First()) : null;
                DateTime? endlossDate = querlossDate != null ? Ext.GetDateTime(querlossDate.Last()) : null;
                //销户日期
                List<string> queryCancelDate = input.cancelDate != null ? input.cancelDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startCancelDate = queryCancelDate != null ? Ext.GetDateTime(queryCancelDate.First()) : null;
                DateTime? endCancelDate = queryCancelDate != null ? Ext.GetDateTime(queryCancelDate.Last()) : null;
                var data = await _db.Queryable<EmployeeEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    //状态标记
                    .Where(u => u.AccStatus == 4)
                    //删除标记
                    .Where(u => u.DeleteMark == 0)
                    //员工类型
                    .WhereIF(!string.IsNullOrEmpty(input.employeType), p => p.EmployeType.Equals(input.employeType))
                     //卡片类型
                     .WhereIF(!string.IsNullOrEmpty(input.cardTypeId), p => p.CardTypeId.Equals(input.cardTypeId))
                    //组织机构
                    .WhereIF(organizeIds.Any(), u => organizeIds.Contains(SqlFunc.ToString(u.DepartId)))
                    //关键字查询
                    .WhereIF(!input.keyword.IsNullOrEmpty(), u => u.JobNum.Contains(input.keyword) || u.RealName.Contains(input.keyword) || u.MobilePhone.Contains(input.keyword))
                    //卡号查询
                    .WhereIF(!string.IsNullOrEmpty(input.cardNo), u => u.CardNo.Contains(input.cardNo) || u.CatCardNo.Contains(input.cardNo))
                    //挂失日期
                    .WhereIF(querlossDate != null, u => u.LossAccDate >= new DateTime(startlossDate.ToDate().Year, startlossDate.ToDate().Month, startlossDate.ToDate().Day, 0, 0, 0))
                    .WhereIF(querlossDate != null, u => u.LossAccDate <= new DateTime(endlossDate.ToDate().Year, endlossDate.ToDate().Month, endlossDate.ToDate().Day, 23, 59, 59))
                    //销户日期
                    .WhereIF(queryCancelDate != null, u => u.CancelAccDate >= new DateTime(startCancelDate.ToDate().Year, startCancelDate.ToDate().Month, startCancelDate.ToDate().Day, 0, 0, 0))
                    .WhereIF(queryCancelDate != null, u => u.CancelAccDate <= new DateTime(endCancelDate.ToDate().Year, endCancelDate.ToDate().Month, endCancelDate.ToDate().Day, 23, 59, 59))
                    .Select(it => new EmployeeListOutput
                    {
                        employeeId = it.EmployeeId,
                        jobNum = it.JobNum,
                        realName = it.RealName,
                        gender = it.Gender,
                        employeType = it.EmployeType,
                        departId = it.DepartId,
                        departName = it.DepartName,
                        headIcon = it.HeadIcon,
                        mobilePhone = it.MobilePhone,
                        isCard = it.IsCard,
                        cardNo = it.CardNo,
                        catCardNo = it.CatCardNo, //长安通卡号
                        expiryEndDate = it.ExpiryEndDate,
                        welfareBalance = it.WelfareBalance,
                        rechargeBalance = it.RechargeBalance,
                        accStatus = it.AccStatus,
                        description = it.Description,
                        LossAccDate = it.LossAccDate,
                        CancelAccDate = it.CancelAccDate,
                        CreatorTime = it.CreatorTime,
                        cardUID = it.CardUID,
                        cardTypeId = it.CardTypeId,
                        cardTypeName = it.CardTypeName,
                        uni_is = it.uni_is,
                        uni_admitGuid = it.uni_admitGuid,
                        uni_faceGuid = it.uni_faceGuid,
                        uni_faceurl = it.uni_faceurl,
                        sortCode = it.SortCode
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<EmployeeListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }

        /// <summary>
        /// 下属机构
        /// </summary>
        /// <param name="organizeId">机构ID</param>
        /// <returns></returns>
        [NonAction]
        public async Task<List<string>> GetSubOrganizeIds(string organizeId)
        {
            var data = await _organizeService.GetListAsync();
            data = data.TreeChildNode(organizeId, t => t.Id, t => t.ParentId);
            return data.Select(m => m.Id).ToList();
        }
        #endregion

        #region Post
        /// <summary>
        /// 新建人员管理
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] EmployeeCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = input.Adapt<EmployeeEntity>();
                var chkEmployee = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.JobNum == input.jobNum && p.CompanyId == userInfo.companyId);
                if (chkEmployee != null)
                {
                    throw PARKException.Bah("所填工号已占用,工号不可重复！");
                }
                if (!string.IsNullOrEmpty(input.mobilePhone) && input.mobilePhone.Length > 0)
                {
                    //处理手机号
                    entity.MobilePhone = Regex.Replace(input.mobilePhone, "(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                    //加密手机号
                    SM4Utils sm4 = new SM4Utils();
                    sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
                    sm4.hexString = false;
                    entity.MobilePhoneSf = sm4.Encrypt_ECB(input.mobilePhone);
                    //验证手机号是否重复
                    chkEmployee = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.MobilePhoneSf == entity.MobilePhoneSf && p.DeleteMark == 0 && p.AccStatus != 4 && p.CompanyId == userInfo.companyId);
                    if (chkEmployee != null)
                    {
                        throw PARKException.Bah("当前手机号被[" + chkEmployee.JobNum + "/" + chkEmployee.RealName + "]使用中,请核查！");
                    }
                }
                if (string.IsNullOrEmpty(input.cardNo))
                {
                    //生成卡号
                    var Paras = new List<SugarParameter>();
                    Paras.Add(new SugarParameter("@v_CardNo", null, true));
                    _db.Ado.UseStoredProcedure().ExecuteCommand("P_Public_AutoCreateCardNo", Paras);
                    object _obj = Paras[0].Value;
                    if (_obj != null)
                    {
                        //生成卡号
                        entity.CardNo = _obj.ToString();
                    }
                    else
                    {
                        entity.CardNo = YitIdHelper.NextId().ToString();
                    }
                    entity.CatCardNo = entity.CardNo;
                }                
                if (!string.IsNullOrEmpty(entity.CardNo))
                {
                    chkEmployee = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.CardNo == entity.CardNo && p.DeleteMark == 0 && p.AccStatus != 4 && p.CompanyId == userInfo.companyId);
                    if (chkEmployee != null)
                    {
                        throw PARKException.Bah("当前卡片被[" + chkEmployee.JobNum + "/" + chkEmployee.RealName + "]使用中,请核查！");
                    }
                }
                entity.CompanyId = userInfo.companyId;
                entity.CompanyName = userInfo.companyName;               
                //获取人员类型
                var chkCardtype = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.Id == entity.CardTypeId && p.IsDeleted == 0 && p.CompanyId == userInfo.companyId);
                if (chkCardtype == null)
                {
                    throw PARKException.Bah("所选员工类型已删除,请核查！");
                }
                else
                {
                    entity.CardTypeName = chkCardtype.CardTypeName;
                    entity.CardTypeCode = chkCardtype.CardTypeCode;
                    entity.Create();
                    if (!string.IsNullOrEmpty(input.departId))
                    {
                        var _OrganizeEntity = await _db.Queryable<OrganizeEntity>().FirstAsync(p => p.Id == input.departId);
                        if (_OrganizeEntity != null)
                        {
                            entity.DepartName = _OrganizeEntity.FullName;
                        }
                    }
                    try
                    {
                        if (input.authMenu == true)
                        {
                            entity.AuthTsMenu = 1;
                        }
                        else
                        {
                            entity.AuthTsMenu = 0;
                        }
                        //开启事务
                        _db.BeginTran();

                        #region 写入日志
                        var ClassEntityList = new List<EmployeeLogEntity>();
                        var _EmployeeLogEntity = new EmployeeLogEntity();
                        _EmployeeLogEntity = entity.Adapt<EmployeeLogEntity>();
                        _EmployeeLogEntity.CompanyId = userInfo.companyId;
                        _EmployeeLogEntity.CompanyName = userInfo.companyName;
                        _EmployeeLogEntity.Create();
                        _EmployeeLogEntity.LogKind = 1;
                        _EmployeeLogEntity.LogKindName = "开户发卡";
                        _EmployeeLogEntity.JobNo = entity.JobNum;
                        _EmployeeLogEntity.ReallName = entity.RealName;
                        var tisOk = await _db.Insertable(_EmployeeLogEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                        #endregion

                        if (!(tisOk > 0))
                        {
                            _db.RollbackTran();
                            throw PARKException.Oh(ErrorCode.COM1000);
                        }
                        var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                        if (!(isOk > 0))
                        {
                            _db.RollbackTran();
                            throw PARKException.Oh(ErrorCode.COM1000);
                        }
                        else
                        {
                            #region 写入人员同步任务
                            var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                            //获取此卡类型对应的消费机
                            var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                            _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                            var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                            if(_MachineList!=null && _MachineList.Rows.Count > 0)
                            {
                                for (int i = 0; i < _MachineList.Rows.Count; i++)
                                {
                                    var MachEye = new MachineEmployeeEntity();
                                    MachEye.Create();
                                    MachEye.EmployeeId = entity.EmployeeId;
                                    MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();                                    
                                    MachEye.EvtType = 1; //新增                                    
                                    MachEye.TaskStatus = 0; //待执行
                                    MachEye.TaskDate = DateTime.Now;
                                    MachEye.CompanyId = entity.CompanyId;
                                    MachEye.CompanyName = entity.CompanyName;
                                    _MachineEmployeeList.Add(MachEye);
                                }
                                if(_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                                {
                                    tisOk = await _db.Insertable(_MachineEmployeeList).ExecuteCommandAsync();
                                }
                            }
                            #endregion

                            var _appInfo = _parkCacheRepository.GetCacheUniubiAppInfo(userInfo.companyId);
                            if (_appInfo != null && _appInfo.uni_is>0)
                            {
                                //调用宇泛接口
                                var dpfout = _uniubiSdkRepository.eyeCreate(entity.JobNum, entity.RealName, entity.CardNo, entity.CompanyId);
                                //更新宇泛人员id
                                if (dpfout.code == "WO_SUS1000")
                                {
                                    var data = dpfout.data.ToObject();
                                    var sqladmitGuid = "update base_employee set uni_admitGuid='" + data["admitGuid"] + "' where EmployeeId='" + entity.EmployeeId + "'";
                                    var isyfOk = await _db.Ado.ExecuteCommandAsync(sqladmitGuid);
                                }
                            } 
                        }                        
                        //关闭事务
                        _db.CommitTran();
                    }
                    catch (Exception ex)
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1000);
                    }
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        /// <summary>
        /// 更新人员管理
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] EmployeeUpInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = input.Adapt<EmployeeEntity>();
                var chkEmployee = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.JobNum == input.jobNum && p.EmployeeId != id && p.CompanyId == userInfo.companyId);
                if (chkEmployee != null)
                {
                    throw PARKException.Bah("所填工号已占用,工号不可重复！");
                }
                if (string.IsNullOrEmpty(input.cardNo))
                {
                    //生成卡号
                    var Paras = new List<SugarParameter>();
                    Paras.Add(new SugarParameter("@v_CardNo", null, true));
                    _db.Ado.UseStoredProcedure().ExecuteCommand("P_Public_AutoCreateCardNo", Paras);
                    object _obj = Paras[0].Value;
                    if (_obj != null)
                    {
                        //生成卡号
                        entity.CardNo = _obj.ToString();
                    }
                    else
                    {
                        entity.CardNo = YitIdHelper.NextId().ToString();
                    }
                    entity.CatCardNo = entity.CardNo;
                }
                if (!string.IsNullOrEmpty(entity.CardNo))
                {
                    chkEmployee = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId != id && p.CardNo == entity.CardNo && p.DeleteMark == 0 && p.AccStatus != 4 && p.CompanyId == userInfo.companyId);
                    if (chkEmployee != null)
                    {
                        throw PARKException.Bah("当前卡片被[" + chkEmployee.JobNum + "/" + chkEmployee.RealName + "]使用中,请核查！");
                    }
                }
                if (!string.IsNullOrEmpty(input.mobilePhone) && input.mobilePhone.Length > 0)
                {
                    //处理手机号
                    entity.MobilePhone = Regex.Replace(input.mobilePhone, "(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                    //加密手机号
                    SM4Utils sm4 = new SM4Utils();
                    sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
                    sm4.hexString = false;
                    entity.MobilePhoneSf = sm4.Encrypt_ECB(input.mobilePhone);
                    //验证手机号是否重复
                    chkEmployee = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId != id && p.MobilePhoneSf == entity.MobilePhoneSf && p.DeleteMark == 0 && p.AccStatus != 4 && p.CompanyId == userInfo.companyId);
                    if (chkEmployee != null)
                    {
                        throw PARKException.Bah("当前手机号被[" + chkEmployee.JobNum + "/" + chkEmployee.RealName + "]使用中,请核查！");
                    }
                }
                //获取人员类型
                var chkCardtype = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.Id == entity.CardTypeId && p.IsDeleted == 0 && p.CompanyId == userInfo.companyId);
                if (chkCardtype == null)
                {
                    throw PARKException.Bah("所选员工类型已删除,请核查！");
                }
                else
                {
                    entity.CardTypeName = chkCardtype.CardTypeName;
                    entity.CardTypeCode = chkCardtype.CardTypeCode;
                    entity.LastModify(id);
                    if (!string.IsNullOrEmpty(input.departId))
                    {
                        var _OrganizeEntity = await _db.Queryable<OrganizeEntity>().FirstAsync(p => p.Id == input.departId);
                        if (_OrganizeEntity != null)
                        {
                            entity.DepartName = _OrganizeEntity.FullName;
                        }
                    }
                    try
                    {
                        var _AuthTsMenu = 0;
                        if (input.authMenu == true)
                        {
                            _AuthTsMenu = 1;
                        }
                        var OldEntity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == id);
                        _db.BeginTran();
                        if (entity.ExpiryEndDate > DateTime.Now)
                        {
                            entity.OverdueStatus = 0;
                        }
                        else
                        {
                            entity.OverdueStatus = 1; //超期
                        }
                        entity.CompanyId = OldEntity.CompanyId;
                        entity.CompanyName = OldEntity.CompanyName;
                        var Paras = new List<SugarParameter>();
                        StringBuilder dbSql = new StringBuilder();
                        dbSql.Append("update base_employee set ");
                        dbSql.AppendFormat("EmployeType='{0}',", entity.EmployeType);
                        dbSql.AppendFormat("ExpiryEndDate='{0}',EmpUpdate='{1}',IsNeedDel=0,", Convert.ToDateTime(entity.ExpiryEndDate).ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        dbSql.AppendFormat("JobNum='{0}',RealName='{1}',Gender={2},", entity.JobNum, entity.RealName, entity.Gender);
                        dbSql.AppendFormat("DepartId='{0}',DepartName='{1}',HeadIcon='{2}',", entity.DepartId, entity.DepartName, entity.HeadIcon);
                        dbSql.AppendFormat("Description='{0}',catCardNo='{1}',", entity.Description, input.catCardNo);
                        dbSql.AppendFormat("MobilePhone='{0}',MobilePhoneSf='{1}',authTsMenu={2},", entity.MobilePhone, entity.MobilePhoneSf, _AuthTsMenu);
                        dbSql.AppendFormat("CardUID='{0}',CardTypeId='{1}',CardTypeName='{2}',CardTypeCode='{3}',", entity.CardUID, entity.CardTypeId, entity.CardTypeName, entity.CardTypeCode);
                        dbSql.AppendFormat("Eyejob='{0}',OverdueStatus='{1}'", entity.Eyejob, entity.OverdueStatus);
                        //卡户信息
                        if (!string.IsNullOrEmpty(entity.CardNo))
                        {
                            dbSql.AppendFormat(",CardNo='{0}',IsCard=1", entity.CardNo);
                        }
                        dbSql.AppendFormat(" where EmployeeId='{0}'", id);
                        var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                        if (!(isOk > 0))
                        {
                            //回滚事务
                            _db.RollbackTran();
                            throw PARKException.Oh(ErrorCode.COM1001);
                        }
                        else
                        {
                            #region 写入人员同步任务
                            var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                            //获取此卡类型对应的消费机
                            var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                            _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                            var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                            if (_MachineList != null && _MachineList.Rows.Count > 0)
                            {
                                for (int i = 0; i < _MachineList.Rows.Count; i++)
                                {
                                    var MachEye = new MachineEmployeeEntity();
                                    MachEye.Create();
                                    MachEye.EmployeeId = entity.EmployeeId;
                                    MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();
                                    MachEye.EvtType = 2; //编辑                                    
                                    MachEye.TaskStatus = 0; //待执行
                                    MachEye.TaskDate = DateTime.Now;
                                    MachEye.CompanyId = entity.CompanyId;
                                    MachEye.CompanyName = entity.CompanyName;
                                    _MachineEmployeeList.Add(MachEye);
                                }
                                if (_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                                {
                                    isOk = await _db.Insertable(_MachineEmployeeList).ExecuteCommandAsync();
                                }
                            }
                            #endregion

                            #region 换卡业务处理
                            if (!string.IsNullOrEmpty(OldEntity.CardNo) && !string.IsNullOrEmpty(entity.CardNo) && OldEntity.CardNo != entity.CardNo)
                            {
                                //写入卡户日志(换卡)
                                var ClassEntityList = new List<EmployeeLogEntity>();
                                var _EmployeeLogEntity = new EmployeeLogEntity();
                                _EmployeeLogEntity = entity.Adapt<EmployeeLogEntity>();
                                _EmployeeLogEntity.CompanyId = userInfo.companyId;
                                _EmployeeLogEntity.CompanyName = userInfo.companyName;
                                _EmployeeLogEntity.Create();
                                _EmployeeLogEntity.LogKind = 6;
                                _EmployeeLogEntity.LogKindName = "补卡";
                                _EmployeeLogEntity.JobNo = entity.JobNum;
                                _EmployeeLogEntity.ReallName = entity.RealName;
                                _EmployeeLogEntity.CardNo = OldEntity.CardNo;
                                _EmployeeLogEntity.NewCardNo = entity.CardNo;
                                var ctisOk = await _db.Insertable(_EmployeeLogEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                                if (!(ctisOk > 0))
                                {
                                    throw PARKException.Oh(ErrorCode.COM1000);
                                }
                            }
                            //调用宇泛接口
                            var dpfout = _uniubiSdkRepository.eyeEdit(entity.uni_admitGuid, entity.JobNum, entity.RealName, entity.CardNo, OldEntity.CompanyId);
                            #endregion

                            _db.CommitTran();
                        }

                        var _appInfo = _parkCacheRepository.GetCacheUniubiAppInfo(userInfo.companyId);
                        if (_appInfo != null && _appInfo.uni_is > 0 && !string.IsNullOrEmpty(entity.uni_admitGuid))
                        {
                            //调用宇泛接口
                            _uniubiSdkRepository.eyeEdit(entity.uni_admitGuid, entity.JobNum, entity.RealName, entity.CardNo, userInfo.companyId);
                        }
                    }
                    catch (Exception ex)
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1000);
                    }
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion

        #region 禁用/启用
        /// <summary>
        /// 更新用户状态(禁用/启用)
        /// </summary>
        /// <returns></returns>
        [HttpPut("{id}/Actions/State")]
        public async Task updateEmployeeState(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                //检测是否已有消费
                try
                {
                    //开启事务
                    _db.BeginTran();
                    if (entity.AccStatus == 1)
                    {
                        //修改账户状态(禁用)
                        var Paras = new List<SugarParameter>();
                        StringBuilder dbSql = new StringBuilder();
                        dbSql.Append("update base_employee set ");
                        dbSql.AppendFormat("AccStatus=0,IsNeedDel=1,EmpUpdate='{0}' ", DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
                        dbSql.AppendFormat(" where EmployeeId='{0}'", id);
                        var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                        if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);
                        //写入日志
                        var ClassEntityList = new List<EmployeeLogEntity>();
                        var _EmployeeLogEntity = new EmployeeLogEntity();
                        _EmployeeLogEntity = entity.Adapt<EmployeeLogEntity>();
                        _EmployeeLogEntity.CompanyId = userInfo.companyId;
                        _EmployeeLogEntity.CompanyName = userInfo.companyName;
                        _EmployeeLogEntity.Create();
                        _EmployeeLogEntity.LogKind = 4;
                        _EmployeeLogEntity.LogKindName = "禁用";
                        _EmployeeLogEntity.JobNo = entity.JobNum;
                        _EmployeeLogEntity.ReallName = entity.RealName;
                        var tisOk = await _db.Insertable(_EmployeeLogEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                        if (!(tisOk > 0))
                        {
                            throw PARKException.Oh(ErrorCode.COM1000);
                        }
                        else
                        {
                            #region 写入人员同步任务
                            var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                            //获取此卡类型对应的消费机
                            var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                            _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                            var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                            if (_MachineList != null && _MachineList.Rows.Count > 0)
                            {
                                for (int i = 0; i < _MachineList.Rows.Count; i++)
                                {
                                    var MachEye = new MachineEmployeeEntity();
                                    MachEye.Create();
                                    MachEye.EmployeeId = entity.EmployeeId;
                                    MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();
                                    MachEye.EvtType = -1; //删除                                    
                                    MachEye.TaskStatus = 0; //待执行
                                    MachEye.TaskDate = DateTime.Now;
                                    MachEye.CompanyId = entity.CompanyId;
                                    MachEye.CompanyName = entity.CompanyName;
                                    _MachineEmployeeList.Add(MachEye);
                                }
                                if (_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                                {
                                    isOk = await _db.Insertable(_MachineEmployeeList).ExecuteCommandAsync();
                                }
                            }
                            #endregion
                        }
                    }
                    if (entity.AccStatus == 0)
                    {
                        //修改账户状态(启用)
                        var Paras = new List<SugarParameter>();
                        StringBuilder dbSql = new StringBuilder();
                        dbSql.Append("update base_employee set ");
                        dbSql.AppendFormat("AccStatus=1,IsNeedDel=0,EmpUpdate='{0}' ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        dbSql.AppendFormat(" where EmployeeId='{0}'", id);
                        var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                        if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);
                        //写入日志
                        var ClassEntityList = new List<EmployeeLogEntity>();
                        var _EmployeeLogEntity = new EmployeeLogEntity();
                        _EmployeeLogEntity = entity.Adapt<EmployeeLogEntity>();
                        _EmployeeLogEntity.CompanyId = userInfo.companyId;
                        _EmployeeLogEntity.CompanyName = userInfo.companyName;
                        _EmployeeLogEntity.Create();
                        _EmployeeLogEntity.LogKind = 5;
                        _EmployeeLogEntity.LogKindName = "启用";
                        _EmployeeLogEntity.JobNo = entity.JobNum;
                        _EmployeeLogEntity.ReallName = entity.RealName;
                        var tisOk = await _db.Insertable(_EmployeeLogEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                        if (!(tisOk > 0))
                        {
                            throw PARKException.Oh(ErrorCode.COM1000);
                        }
                        else
                        {
                            #region 写入人员同步任务
                            var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                            //获取此卡类型对应的消费机
                            var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                            _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                            var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                            if (_MachineList != null && _MachineList.Rows.Count > 0)
                            {
                                for (int i = 0; i < _MachineList.Rows.Count; i++)
                                {
                                    var MachEye = new MachineEmployeeEntity();
                                    MachEye.Create();
                                    MachEye.EmployeeId = entity.EmployeeId;
                                    MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();
                                    MachEye.EvtType = 1; //新增                                    
                                    MachEye.TaskStatus = 0; //待执行
                                    MachEye.TaskDate = DateTime.Now;
                                    MachEye.CompanyId = entity.CompanyId;
                                    MachEye.CompanyName = entity.CompanyName;
                                    _MachineEmployeeList.Add(MachEye);
                                }
                                if (_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                                {
                                    isOk = await _db.Insertable(_MachineEmployeeList).ExecuteCommandAsync();
                                }
                            }
                            #endregion
                        }
                    }
                    //关闭事务
                    _db.CommitTran();
                }
                catch (Exception ex)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1002);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion

        #region 挂失、解除挂失
        /// <summary>
        /// 挂失用户
        /// </summary>
        /// <returns></returns>
        [HttpPut("{id}/Actions/loss")]
        public async Task lossEmployeeState(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                //检测是否已有消费
                try
                {
                    //开启事务
                    _db.BeginTran();
                    //修改账户状态
                    entity.LossAccDate = DateTime.Now;
                    var Paras = new List<SugarParameter>();
                    StringBuilder dbSql = new StringBuilder();
                    dbSql.Append("update base_employee set ");
                    dbSql.AppendFormat("AccStatus=3,LossAccDate='{0}',EmpUpdate='{1}',IsNeedDel=1", entity.LossAccDate, DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
                    dbSql.AppendFormat(" where EmployeeId='{0}'", id);
                    var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                    if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);
                    //写入日志
                    var ClassEntityList = new List<EmployeeLogEntity>();
                    var _EmployeeLogEntity = new EmployeeLogEntity();
                    _EmployeeLogEntity = entity.Adapt<EmployeeLogEntity>();
                    _EmployeeLogEntity.CompanyId = userInfo.companyId;
                    _EmployeeLogEntity.CompanyName = userInfo.companyName;
                    _EmployeeLogEntity.Create();
                    _EmployeeLogEntity.LogKind = 2;
                    _EmployeeLogEntity.LogKindName = "挂失";
                    _EmployeeLogEntity.JobNo = entity.JobNum;
                    _EmployeeLogEntity.ReallName = entity.RealName;

                    var tisOk = await _db.Insertable(_EmployeeLogEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                    if (!(tisOk > 0))
                    {
                        throw PARKException.Oh(ErrorCode.COM1000);
                    }
                    else
                    {
                        #region 写入人员同步任务
                        var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                        //获取此卡类型对应的消费机
                        var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                        _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                        var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                        if (_MachineList != null && _MachineList.Rows.Count > 0)
                        {
                            for (int i = 0; i < _MachineList.Rows.Count; i++)
                            {
                                var MachEye = new MachineEmployeeEntity();
                                MachEye.Create();
                                MachEye.EmployeeId = entity.EmployeeId;
                                MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();
                                MachEye.EvtType = -1; //删除                                    
                                MachEye.TaskStatus = 0; //待执行
                                MachEye.TaskDate = DateTime.Now;
                                MachEye.CompanyId = entity.CompanyId;
                                MachEye.CompanyName = entity.CompanyName;
                                _MachineEmployeeList.Add(MachEye);
                            }
                            if (_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                            {
                                isOk = await _db.Insertable(_MachineEmployeeList).ExecuteCommandAsync();
                            }
                        }
                        #endregion
                    }
                    //关闭事务
                    _db.CommitTran();
                }
                catch (Exception ex)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1002);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        /// <summary>
        /// 解挂用户
        /// </summary>
        /// <returns></returns>
        [HttpPut("{id}/Actions/RemoveLoss")]
        public async Task RemovelossEmployeeState(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                //检测是否已有消费
                try
                {
                    //开启事务
                    _db.BeginTran();
                    //修改账户状态
                    var Paras = new List<SugarParameter>();
                    StringBuilder dbSql = new StringBuilder();
                    dbSql.Append("update base_employee set ");
                    dbSql.AppendFormat("AccStatus=1,IsNeedDel=0,EmpUpdate='{0}' ", DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
                    dbSql.AppendFormat(" where EmployeeId='{0}'", id);
                    var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                    if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);
                    //写入日志
                    var ClassEntityList = new List<EmployeeLogEntity>();
                    var _EmployeeLogEntity = new EmployeeLogEntity();
                    _EmployeeLogEntity = entity.Adapt<EmployeeLogEntity>();
                    _EmployeeLogEntity.CompanyId = userInfo.companyId;
                    _EmployeeLogEntity.CompanyName = userInfo.companyName;
                    _EmployeeLogEntity.Create();
                    _EmployeeLogEntity.LogKind = 3;
                    _EmployeeLogEntity.LogKindName = "解挂";
                    _EmployeeLogEntity.JobNo = entity.JobNum;
                    _EmployeeLogEntity.ReallName = entity.RealName;
                    var tisOk = await _db.Insertable(_EmployeeLogEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                    if (!(tisOk > 0))
                    {
                        throw PARKException.Oh(ErrorCode.COM1000);
                    }
                    else
                    {
                        #region 写入人员同步任务
                        var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                        //获取此卡类型对应的消费机
                        var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                        _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                        var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                        if (_MachineList != null && _MachineList.Rows.Count > 0)
                        {
                            for (int i = 0; i < _MachineList.Rows.Count; i++)
                            {
                                var MachEye = new MachineEmployeeEntity();
                                MachEye.Create();
                                MachEye.EmployeeId = entity.EmployeeId;
                                MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();
                                MachEye.EvtType = 1; //新增                                    
                                MachEye.TaskStatus = 0; //待执行
                                MachEye.TaskDate = DateTime.Now;
                                MachEye.CompanyId = entity.CompanyId;
                                MachEye.CompanyName = entity.CompanyName;
                                _MachineEmployeeList.Add(MachEye);
                            }
                            if (_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                            {
                                isOk = await _db.Insertable(_MachineEmployeeList).ExecuteCommandAsync();
                            }
                        }
                        #endregion
                    }
                    //关闭事务
                    _db.CommitTran();
                }
                catch (Exception ex)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1002);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion

        #region 销户
        /// <summary>
        /// 注销用户
        /// </summary>
        /// <returns></returns>
        [HttpPut("{id}/Actions/Logout")]
        public async Task logoutEmployeeState(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                /*
                if (entity.WelfareBalance > 0 || entity.RechargeBalance > 0)
                {
                    throw PARKException.Bah("余额大于0,不允许销户!");
                }
                */
                //检测是否已有消费
                try
                {
                    //开启事务
                    _db.BeginTran();
                    //修改账户状态
                    entity.CancelAccDate = DateTime.Now;
                    var Paras = new List<SugarParameter>();
                    StringBuilder dbSql = new StringBuilder();
                    dbSql.Append("update base_employee set ");
                    dbSql.AppendFormat("AccStatus=4,CancelAccDate='{0}',Isauth=0,wId=null,Authtimes=null,EmpUpdate='{1}',IsNeedDel=1", entity.CancelAccDate, DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
                    dbSql.AppendFormat("where EmployeeId='{0}'", id);
                    var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                    if (!(isOk > 0))
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1001);
                    }

                    //写入日志
                    var ClassEntityList = new List<EmployeeLogEntity>();
                    var _EmployeeLogEntity = new EmployeeLogEntity();
                    _EmployeeLogEntity = entity.Adapt<EmployeeLogEntity>();
                    _EmployeeLogEntity.CompanyId = userInfo.companyId;
                    _EmployeeLogEntity.CompanyName = userInfo.companyName;
                    _EmployeeLogEntity.Create();
                    _EmployeeLogEntity.LogKind = 7;
                    _EmployeeLogEntity.LogKindName = "销户";
                    _EmployeeLogEntity.JobNo = entity.JobNum;
                    _EmployeeLogEntity.ReallName = entity.RealName;
                    _EmployeeLogEntity.CompanyId = userInfo.companyId;
                    _EmployeeLogEntity.CompanyName = userInfo.companyName;
                    var tisOk = await _db.Insertable(_EmployeeLogEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                    if (!(tisOk > 0))
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1000);
                    }
                    else
                    {
                        #region 写入人员同步任务
                        var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                        //获取此卡类型对应的消费机
                        var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                        _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                        var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                        if (_MachineList != null && _MachineList.Rows.Count > 0)
                        {
                            for (int i = 0; i < _MachineList.Rows.Count; i++)
                            {
                                var MachEye = new MachineEmployeeEntity();
                                MachEye.Create();
                                MachEye.EmployeeId = entity.EmployeeId;
                                MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();
                                MachEye.EvtType = -1; //删除                                    
                                MachEye.TaskStatus = 0; //待执行
                                MachEye.TaskDate = DateTime.Now;
                                MachEye.CompanyId = entity.CompanyId;
                                MachEye.CompanyName = entity.CompanyName;
                                _MachineEmployeeList.Add(MachEye);
                            }
                            if (_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                            {
                                isOk = await _db.Insertable(_MachineEmployeeList).ExecuteCommandAsync();
                            }
                        }
                        #endregion

                        #region  处理微信绑定
                        var Paras1 = new List<SugarParameter>();
                        StringBuilder dbSql1 = new StringBuilder();
                        dbSql1.Append("delete from base_employee_wechat ");
                        dbSql1.AppendFormat(" where EmployeeId='{0}'", id);
                        await _db.Ado.ExecuteCommandAsync(dbSql1.ToString(), Paras1);
                        #endregion

                        #region 写入退款申请
                        var mch_id = _db.Queryable<SysConfigEntity>().First(s => s.Category == "WxPayConfig" && s.Key == "wx_mch_id" && s.CompanyId == userInfo.companyId).Value; //1632719416
                        var _ConsumRefundEntity = new ConsumRefundEntity();
                        _ConsumRefundEntity.Create();
                        _ConsumRefundEntity.CardNo = entity.CardNo;
                        _ConsumRefundEntity.CatCardNo = entity.CatCardNo;
                        _ConsumRefundEntity.CompanyId = entity.CompanyId;
                        _ConsumRefundEntity.CompanyName = entity.CompanyName;
                        _ConsumRefundEntity.DbDate = DateTime.Now;
                        _ConsumRefundEntity.DepartId = entity.DepartId;
                        _ConsumRefundEntity.DepartName = entity.DepartName;
                        _ConsumRefundEntity.EmployeeId = entity.EmployeeId;
                        _ConsumRefundEntity.JobNo = entity.JobNum;
                        _ConsumRefundEntity.ReallName = entity.RealName;

                        _ConsumRefundEntity.IsNeedRefund = entity.RechargeBalance > 0 ? 1 : 0;
                        _ConsumRefundEntity.billStatus  = entity.RechargeBalance > 0 ? 1 : 0;
                        _ConsumRefundEntity.billStatusName = entity.RechargeBalance > 0 ? "等待退款" : "无需退款";
                        _ConsumRefundEntity.IsAny = 0;
                        _ConsumRefundEntity.AuditDate = DateTime.Now;
                        _ConsumRefundEntity.out_refund_no = GenerateOutTradeNo(mch_id);
                        _ConsumRefundEntity.rechargeId = "";
                        _ConsumRefundEntity.IsRefund = 0;
                        _ConsumRefundEntity.out_trade_no = "";
                        _ConsumRefundEntity.totalAmt = 0;
                        _ConsumRefundEntity.refundAmt = entity.RechargeBalance;
                        _ConsumRefundEntity.transaction_id = "";
                        _ConsumRefundEntity.Summary = "销户,退账户余额";
                        _ConsumRefundEntity.IsMain = 1;
                        tisOk = await _db.Insertable(_ConsumRefundEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                        if (!(tisOk > 0))
                        {
                            //回滚事务
                            _db.RollbackTran();
                            throw PARKException.Oh(ErrorCode.COM1000);
                        }
                        #endregion
                    }
                    //关闭事务
                    _db.CommitTran();

                    //调用宇泛接口
                    var _appInfo = _parkCacheRepository.GetCacheUniubiAppInfo(userInfo.companyId);
                    if (_appInfo != null && _appInfo.uni_is > 0 && !string.IsNullOrEmpty(entity.uni_admitGuid))
                    {
                        _uniubiSdkRepository.eyeDelete(entity.uni_admitGuid, entity.CompanyId);
                    }
                }
                catch (Exception ex)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1001);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion

        #region 销户后重新启用账户
        /// <summary>
        /// 销户后启用账户
        /// </summary>
        /// <returns></returns>
        [HttpPut("{id}/Actions/EnableAgain")]
        public async Task enableagainEmployeeState(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                try
                {
                    //开启事务
                    _db.BeginTran();
                    //修改账户状态
                    var Paras = new List<SugarParameter>();
                    StringBuilder dbSql = new StringBuilder();
                    dbSql.Append("update base_employee set ");
                    dbSql.AppendFormat("AccStatus=1,Isauth=0,Authtimes=NULL,wId=NULL,IsNeedDel =0 ");
                    dbSql.AppendFormat(" where EmployeeId='{0}'", id);
                    var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                    if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);

                    #region  处理微信绑定
                    var Paras1 = new List<SugarParameter>();
                    StringBuilder dbSql1 = new StringBuilder();
                    dbSql1.Append("delete from base_employee_wechat ");
                    dbSql1.AppendFormat(" where EmployeeId='{0}'", id);
                    await _db.Ado.ExecuteCommandAsync(dbSql1.ToString(), Paras1);
                    #endregion

                    //写入日志
                    var ClassEntityList = new List<EmployeeLogEntity>();
                    var _EmployeeLogEntity = new EmployeeLogEntity();
                    _EmployeeLogEntity = entity.Adapt<EmployeeLogEntity>();
                    _EmployeeLogEntity.CompanyId = userInfo.companyId;
                    _EmployeeLogEntity.CompanyName = userInfo.companyName;
                    _EmployeeLogEntity.Create();
                    _EmployeeLogEntity.LogKind = 8;
                    _EmployeeLogEntity.LogKindName = "重新启用";
                    _EmployeeLogEntity.JobNo = entity.JobNum;
                    _EmployeeLogEntity.ReallName = entity.RealName;
                    var tisOk = await _db.Insertable(_EmployeeLogEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                    if (!(tisOk > 0))
                    {
                        throw PARKException.Oh(ErrorCode.COM1000);
                    }
                    else
                    {
                        #region 写入人员同步任务
                        var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                        //获取此卡类型对应的消费机
                        var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                        _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                        var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                        if (_MachineList != null && _MachineList.Rows.Count > 0)
                        {
                            for (int i = 0; i < _MachineList.Rows.Count; i++)
                            {
                                var MachEye = new MachineEmployeeEntity();
                                MachEye.Create();
                                MachEye.EmployeeId = entity.EmployeeId;
                                MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();
                                MachEye.EvtType = 1; //新增                                    
                                MachEye.TaskStatus = 0; //待执行
                                MachEye.TaskDate = DateTime.Now;
                                MachEye.CompanyId = entity.CompanyId;
                                MachEye.CompanyName = entity.CompanyName;
                                _MachineEmployeeList.Add(MachEye);
                            }
                            if (_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                            {
                                isOk = await _db.Insertable(_MachineEmployeeList).ExecuteCommandAsync();
                            }
                        }
                        #endregion
                    }
                    //关闭事务
                    _db.CommitTran();
                }
                catch (Exception ex)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1002);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion

        #region 删除人员管理
        /// <summary>
        /// 删除人员管理
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.EmployeeId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                if (entity.WelfareBalance > 0 || entity.RechargeBalance > 0)
                {
                    throw PARKException.Bah("余额大于0,不允许删除!");
                }
                try
                {
                    _db.BeginTran();
                    var Paras = new List<SugarParameter>();
                    StringBuilder dbSql = new StringBuilder();
                    dbSql.Append("update base_employee set ");
                    dbSql.AppendFormat(" F_DeleteMark=1,F_DeleteTime='{0}',EmpUpdate='{0}',", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    dbSql.AppendFormat(" F_DeleteUserId='{0}',F_DeleteUserName='{1}',AccStatus=0,IsNeedDel=1", userInfo.userId, userInfo.userName);
                    dbSql.AppendFormat(" where EmployeeId='{0}'", id);
                    var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
                    if (!(isOk > 0))
                    {
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1001);
                    }
                    else
                    {
                        #region 写入人员同步任务
                        var _MachineEmployeeList = new List<MachineEmployeeEntity>();
                        //获取此卡类型对应的消费机
                        var _dbSql = new StringBuilder("select distinct MachineId from consum_machine_cardtype ");
                        _dbSql.AppendFormat(" where CardTypeId='{0}' and CompanyId='{1}'", entity.CardTypeId, entity.CompanyId);
                        var _MachineList = await _db.SqlQueryable<DataTable>(_dbSql.ToString()).ToDataTableAsync();
                        if (_MachineList != null && _MachineList.Rows.Count > 0)
                        {
                            for (int i = 0; i < _MachineList.Rows.Count; i++)
                            {
                                var MachEye = new MachineEmployeeEntity();
                                MachEye.Create();
                                MachEye.EmployeeId = entity.EmployeeId;
                                MachEye.MachineId = _MachineList.Rows[i]["MachineId"].ToString();
                                MachEye.EvtType = -1; //删除                                    
                                MachEye.TaskStatus = 0; //待执行
                                MachEye.TaskDate = DateTime.Now;
                                MachEye.CompanyId = entity.CompanyId;
                                MachEye.CompanyName = entity.CompanyName;
                                _MachineEmployeeList.Add(MachEye);
                            }
                            if (_MachineEmployeeList != null && _MachineEmployeeList.Count > 0)
                            {
                                isOk = await _db.Insertable(_MachineEmployeeList).ExecuteCommandAsync();
                            }
                        }
                        #endregion

                        #region  处理微信绑定
                        var Paras1 = new List<SugarParameter>();
                        StringBuilder dbSql1 = new StringBuilder();
                        dbSql1.Append("delete from base_employee_wechat ");
                        dbSql1.AppendFormat(" where EmployeeId='{0}'", id);
                        await _db.Ado.ExecuteCommandAsync(dbSql1.ToString(), Paras1);
                        #endregion
                    }

                    var _appInfo = _parkCacheRepository.GetCacheUniubiAppInfo(userInfo.companyId);
                    if (_appInfo != null && _appInfo.uni_is > 0 && !string.IsNullOrEmpty(entity.uni_admitGuid))
                    {
                        //调用宇泛接口
                        _uniubiSdkRepository.eyeDelete(entity.uni_admitGuid, entity.CompanyId);
                    }
                    _db.CommitTran();
                }
                catch (Exception ex)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1002);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion

        #region 批量修改卡户有效期
        /// <summary>
        /// 批量修改卡户有效期
        /// </summary>
        /// <param name="input">批量修改卡户有效期对象</param>
        /// <returns></returns>
        [HttpPut("BatchUpdateExpiryDate")]
        public async Task BatchUpdateExpiryDate(BatchUpdateExpiryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                string[] _eyeIds = input.eyeIds.Split(",".ToCharArray());
                string id = "";
                foreach (var item in _eyeIds)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        id += "'" + item + "',";
                    }
                }
                id = id.Length > 0 ? id.Substring(0, id.Length - 1) : "";
                DateTime? _ExpiryDate = input.expiryEndDate;
                StringBuilder dbSql = new StringBuilder("select * from base_employee a where a.F_DeleteMark=0 ");
                dbSql.AppendFormat(" and a.CompanyId='{0}'", userInfo.companyId);
                dbSql.AppendFormat(" and a.EmployeeId IN (" + id + ")");
                var data = await _db.SqlQueryable<EmployeeEntity>(dbSql.ToString()).Select(it => new EmployeeListOutput
                {
                    employeeId = it.EmployeeId,
                    jobNum = it.JobNum,
                    realName = it.RealName,
                    gender = it.Gender,
                    employeType = it.EmployeType,
                    departId = it.DepartId,
                    departName = it.DepartName,
                    headIcon = it.HeadIcon,
                    mobilePhone = it.MobilePhone,
                    isCard = it.IsCard,
                    cardNo = it.CardNo,
                    catCardNo = it.CatCardNo, //长安通卡号
                    expiryEndDate = it.ExpiryEndDate,
                    welfareBalance = it.WelfareBalance,
                    rechargeBalance = it.RechargeBalance,
                    accStatus = it.AccStatus,
                    description = it.Description,
                    LossAccDate = it.LossAccDate,
                    CancelAccDate = it.CancelAccDate,
                    CreatorTime = it.CreatorTime,
                }).MergeTable().ToListAsync();

                _db.BeginTran();
                foreach (var item in data)
                {
                    var Paras = new List<SugarParameter>();
                    StringBuilder _dbSql = new StringBuilder();
                    _dbSql.Append("update base_employee set ");
                    _dbSql.AppendFormat("ExpiryEndDate='{0}'", Convert.ToDateTime(input.expiryEndDate).ToString("yyyy-MM-dd") + " 23:59:59");
                    _dbSql.AppendFormat(" where EmployeeId='{0}'", item.employeeId);
                    var isOk = await _db.Ado.ExecuteCommandAsync(_dbSql.ToString(), Paras);
                    if (!(isOk > 0))
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1001);
                    }
                }
                _db.CommitTran();
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion

        #region 导入卡户
        /// <summary>
        /// 模板下载
        /// </summary>
        [HttpGet("TemplateDownloademp")]
        public dynamic TemplateDownloademp()
        {
            var filePath = FileVariable.TemplateFilePath + "卡户信息模板.xls";//模板路径
            var addFilePath = FileVariable.TemporaryFilePath + "卡户信息模板.xls";//保存路径
            if (!FileHelper.IsExistFile(addFilePath))
            {
                List<ExcelTemplateModel> templateList = new List<ExcelTemplateModel>();
                ExcelExportHelper<ExcelTemplateModel>.Export(templateList, filePath, addFilePath);
            }
            return new { name = "卡户信息模板.xls", url = "api/File/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|卡户信息模板.xls", "JNPF") };
        }
        /// <summary>
        /// 导入预览
        /// </summary>
        /// <returns></returns>
        [HttpGet("ImportPreviewemp")]
        public async Task<dynamic> ImportPreviewemp(string fileName)
        {
            try
            {
                var userInfo = await _userManager.GetUserInfo();
                if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
                {
                    List<EmployeeListOutput> EmployeeFailResult = new List<EmployeeListOutput>();
                    List<CheckDateerrOutput> FailResult = new List<CheckDateerrOutput>();
                    EmployeeListOutput put = null;
                    var filePath = FileVariable.TemporaryFilePath;
                    var savePath = filePath + fileName;
                    //得到数据
                    var excelData = ExcelImportHelper.ToDataTable(savePath);
                    var IsExistsdep = 0;
                    var IsExistsjobno = 0;
                    var IsExistsname = 0;
                    var IsExistssex = 0;
                    var IsExistscard = 0;
                    var IsExistsaatCard = 0;
                    var IsExistsdate = 0;
                    var IsExistsphone = 0;
                    var IsExiststype = 0;
                    foreach (var item in excelData.Columns)
                    {
                        switch (item.ToString())
                        {
                            case "部门名称":
                                IsExistsdep++;
                                break;
                            case "员工编号":
                                IsExistsjobno++;
                                break;
                            case "姓名":
                                IsExistsname++;
                                break;
                            case "性别":
                                IsExistssex++;
                                break;
                            case "员工类型":
                                IsExiststype++;
                                break;
                            case "卡号":
                                IsExistscard++;
                                break;
                            case "长安通卡号":
                                IsExistsaatCard++;
                                break;
                            case "有效期":
                                IsExistsdate++;
                                break;
                            case "手机号码":
                                IsExistsphone++;
                                break;
                            default:

                                break;
                        }
                    }
                    if (IsExistsdep == 0)
                    {
                        FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [部门名称] 列" });
                    }
                    if (IsExistsjobno == 0)
                    {
                        FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [员工编号] 列" });
                    }
                    if (IsExistsname == 0)
                    {
                        FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [姓名] 列" });
                    }
                    if (IsExistssex == 0)
                    {
                        FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [性别] 列" });
                    }
                    if (IsExiststype == 0)
                    {
                        FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [员工类型] 列" });
                    }
                    if (IsExistscard == 0)
                    {
                        FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [卡号] 列" });
                    }
                    if (IsExistsaatCard == 0)
                    {
                        FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [长安通卡号] 列" });
                    }
                    if (IsExistsdate == 0)
                    {
                        FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [有效期] 列" });
                    }
                    if (IsExistsphone == 0)
                    {
                        FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [手机号码] 列" });
                    }

                    if (IsExistsdep == 0 || IsExistsjobno == 0 || IsExistsname == 0 || IsExistssex == 0 || IsExiststype == 0 || IsExistscard == 0 || IsExistsaatCard == 0 || IsExistsdate == 0 || IsExistsphone == 0)
                    {
                        return new { dataRow = EmployeeFailResult, errRow = FailResult };
                    }
                    foreach (var item in excelData.Columns)
                    {
                        excelData.Columns[item.ToString()].ColumnName = GetFiledEncodeemp(item.ToString());
                    }
                    var _Organizelist = await _db.Queryable<OrganizeEntity>().ToListAsync();
                    //卡户
                    var dataEmployee = await _baseEmployeeRepository.Where(t => t.DeleteMark == 0 && t.CompanyId == userInfo.companyId).ToListAsync();
                    //返回结果
                    if (excelData != null && excelData.Rows.Count > 0)
                    {
                        var _iserr = 0;
                        var _msg = "";
                        for (int i = 0; i < excelData.Rows.Count; i++)
                        {
                            _iserr = 0;
                            _msg = "";
                            put = new EmployeeListOutput();
                            put.departName = Convert.ToString(excelData.Rows[i]["departName"]);
                            //验证部门
                            var _Organize = _Organizelist.Where(p => p.FullName.Equals(put.departName) && p.CompanyId == userInfo.companyId).ToList();
                            if (_Organize != null && _Organize.Count > 0)
                            {
                                put.departId = _Organize[0].Id;
                                put.departName = _Organize[0].FullName;
                            }
                            else
                            {
                                _msg += "[部门] 系统中不存在;";
                                _iserr++;
                            }
                            put.jobNum = Convert.ToString(excelData.Rows[i]["jobNum"]);
                            var items = dataEmployee.Where(p => p.JobNum.Equals(put.jobNum)).ToList();
                            if (items != null && items.Count > 0)
                            {
                                _msg += "[工号] 系统中已存在;";
                                _iserr++;
                            }
                            else
                            {
                                put.jobNum = Convert.ToString(excelData.Rows[i]["jobNum"]);
                            }
                            put.realName = Convert.ToString(excelData.Rows[i]["realName"]);
                            put.genderName = excelData.Rows[i]["genderName"].ToString();
                            if (put.genderName == "男")
                            {
                                put.gender = 1;
                            }
                            else if (put.genderName == "女")
                            {
                                put.gender = 2;
                            }
                            else if (put.genderName == "保密")
                            {
                                put.gender = 3;
                            }
                            put.employeTypeName = excelData.Rows[i]["employeType"].ToString();
                            if (put.employeTypeName == "临时员工")
                            {
                                put.employeType = 2;
                                put.expiryEndDate = Convert.ToDateTime(excelData.Rows[i]["expiryEndDate"]);
                            }
                            else
                            {
                                put.employeType = 1;
                                put.expiryEndDate = DateTime.Now.AddYears(50);
                            }
                            put.cardNo = Convert.ToString(excelData.Rows[i]["cardNo"]);
                            var itemscard = dataEmployee.Where(p => p.CardNo.Equals(put.cardNo)).ToList();
                            if (itemscard != null && itemscard.Count > 0)
                            {
                                _msg += "[卡号] 系统中已存在;";
                                _iserr++;
                            }
                            else
                            {
                                put.cardNo = Convert.ToString(excelData.Rows[i]["cardNo"]);
                            }
                            put.catCardNo = Convert.ToString(excelData.Rows[i]["catCardNo"]);

                            var mobilephone = excelData.Rows[i]["mobilePhone"].ToString();
                            Regex rx = new Regex(@"^(13|14|15|16|17|18|19)\d{9}$", RegexOptions.None);
                            Match m = rx.Match(mobilephone);
                            if (!m.Success)
                            {
                                _msg += "[手机号码] 格式不正确;";
                                _iserr++;
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(excelData.Rows[i]["mobilePhone"].ToString()) && excelData.Rows[i]["mobilePhone"].ToString().Length > 0)
                                {
                                    //处理手机号
                                    put.mobilePhone = Regex.Replace(excelData.Rows[i]["mobilePhone"].ToString(), "(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                                    //加密手机号
                                    SM4Utils sm4 = new SM4Utils();
                                    sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
                                    sm4.hexString = false;
                                    put.mobilePhoneSf = sm4.Encrypt_ECB(excelData.Rows[i]["mobilePhone"].ToString());
                                }
                            }
                            put.description = Convert.ToString(excelData.Rows[i]["description"]);
                            put.CompanyId = userInfo.companyId;
                            put.CompanyName = userInfo.companyName;
                            if (_iserr > 0)
                            {
                                FailResult.Add(new CheckDateerrOutput()
                                {
                                    rowNo = (i + 1).ToString(),
                                    errorMsg = _msg
                                });
                            }
                            else
                            {
                                EmployeeFailResult.Add(put);
                            }
                        }
                    }
                    return new { dataRow = EmployeeFailResult, errRow = FailResult };
                }
                else
                    return null;
            }
            catch (Exception e)
            {

                throw PARKException.Oh(ErrorCode.D1801);
            }
        }
        /// <summary>
        /// 获取字段编码
        /// </summary>
        /// <param name="filed"></param>
        /// <returns></returns>
        private string GetFiledEncodeemp(string filed)
        {
            switch (filed)
            {
                case "部门名称":
                    return "departName";
                case "员工编号":
                    return "jobNum";
                case "姓名":
                    return "realName";
                case "性别":
                    return "genderName";
                case "员工类型":
                    return "employeType";
                case "卡号":
                    return "cardNo";
                case "长安通卡号":
                    return "catCardNo";
                case "有效期":
                    return "expiryEndDate";
                case "手机号码":
                    return "mobilePhone";
                case "备注":
                    return "description";
                default:
                    return "";
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost("Uploaderemp")]
        public async Task<dynamic> Uploaderemp(IFormFile file)
        {
            return await _fileService.Uploader("", file);
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpPost("InDataemp")]
        public async Task<dynamic> InDataemp([FromBody] EmpImportDataInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var output = new EmpImportDataOutput();
            string errMsg = string.Empty;
            foreach (var item in input.EmployeeList)
            {
                try
                {
                    var entity = item.Adapt<EmployeeEntity>();
                    errMsg = "";
                    if (string.IsNullOrEmpty(item.departName))
                    {
                        errMsg += "部门不能为空;";
                    }
                    if (string.IsNullOrEmpty(item.jobNum))
                    {
                        errMsg += "工号不能为空;";
                    }
                    else
                    {
                        var data = await _baseEmployeeRepository.Where(t => t.DeleteMark == 0 && t.JobNum == item.jobNum && t.CompanyId == userInfo.companyId).ToListAsync();
                        if (data.Count > 0)
                        {
                            errMsg += "工号不能重复;";
                        }
                    }
                    if (string.IsNullOrEmpty(item.realName))
                    {
                        errMsg += "姓名不能为空;";
                    }
                    if (string.IsNullOrEmpty(item.genderName))
                    {
                        errMsg += "性别不能为空;";
                    }
                    if (string.IsNullOrEmpty(item.cardNo))
                    {
                        errMsg += "卡号不能为空;";
                    }
                    if (string.IsNullOrEmpty(item.catCardNo))
                    {
                        errMsg += "长安通卡号不能为空;";
                    }
                    if (!string.IsNullOrEmpty(item.genderName))
                    {
                        if (item.genderName != "男" && item.genderName != "女" && item.genderName != "保密")
                        {
                            errMsg += "性别不存在;";
                        }
                    }
                    if (!string.IsNullOrEmpty(item.employeTypeName))
                    {
                        if (item.employeTypeName != "正式员工" && item.employeTypeName != "临时员工")
                        {
                            errMsg += "员工类型不存在;";
                        }
                    }
                    if (string.IsNullOrEmpty(item.mobilePhone))
                    {
                        errMsg += "手机号码不能为空;";
                    }
                    if (errMsg != "")
                    {
                        item.errorMsg = errMsg;
                        output.EmployeeFailResult.Add(item);
                        output.fnum++;
                    }
                    else
                    {
                        output.snum++;
                    }
                }
                catch (Exception ex)
                {
                    item.errorMsg = "发生异常";
                    output.EmployeeFailResult.Add(item);
                    output.fnum++;
                }
            }
            if (output.snum == input.EmployeeList.Count)
            {
                output.resultType = 0;
                //导入成功删除文件
                var filePath = FileVariable.TemporaryFilePath;
                var savePath = filePath + input.fileName;
                FileHelper.DeleteFile(savePath);
                var _Organizelist = await _db.Queryable<OrganizeEntity>().ToListAsync();
                //导入成功写入数据
                foreach (var item in input.EmployeeList)
                {
                    var entity = item.Adapt<EmployeeEntity>();
                    entity.Create();
                    entity.CompanyId = userInfo.companyId;
                    entity.CompanyName = userInfo.companyName;
                    entity.EmployeeId = YitIdHelper.NextId().ToString();
                    try
                    {
                        //设置排序
                        entity.Description = entity.Description + "-" + DateTime.Now + ":导入数据";
                        var _Organize = _Organizelist.Where(t => t.DeleteMark == 0 && t.FullName == entity.DepartName).ToList();
                        if (_Organize.Count > 0)
                        {
                            entity.DepartId = _Organize[0].Id;
                            entity.DepartName = _Organize[0].FullName;
                        }
                        if (!string.IsNullOrEmpty(item.genderName))
                        {
                            if (item.genderName == "男")
                            {
                                entity.Gender = 1;
                            }
                            if (item.genderName == "女")
                            {
                                entity.Gender = 2;
                            }
                            if (item.genderName == "保密")
                            {
                                entity.Gender = 3;
                            }
                        }
                        if (!string.IsNullOrEmpty(item.employeTypeName))
                        {
                            if (item.employeTypeName == "正式员工")
                            {
                                entity.EmployeType = 1;
                            }
                            if (item.employeTypeName == "临时员工")
                            {
                                entity.EmployeType = 2;
                            }
                        }
                        entity.IsCard = 1;
                        //开启事务
                        _db.BeginTran();

                        await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnEntityAsync();
                        //关闭事务
                        _db.CommitTran();
                    }
                    catch (Exception ex)
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1000);
                    }
                }
            }
            else
            {
                output.resultType = -1;
            }
            return output;
        }
        #endregion

        #region 导入充值期初余额
        /// <summary>
        /// 模板下载
        /// </summary>
        [HttpGet("TemplateDownloadrecbl")]
        public dynamic TemplateDownloadrecbl()
        {
            var filePath = FileVariable.TemplateFilePath + "充值期初信息模板.xls";//模板路径
            var addFilePath = FileVariable.TemporaryFilePath + "充值期初信息模板.xls";//保存路径
            if (!FileHelper.IsExistFile(addFilePath))
            {
                List<ExcelTemplateModel> templateList = new List<ExcelTemplateModel>();
                ExcelExportHelper<ExcelTemplateModel>.Export(templateList, filePath, addFilePath);
            }
            return new { name = "充值期初信息模板.xls", url = "api/File/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|充值期初信息模板.xls", "JNPF") };
        }

        /// <summary>
        /// 导入预览
        /// </summary>
        /// <returns></returns>
        [HttpGet("ImportPreviewrecbl")]
        public async Task<dynamic> ImportPreviewrecbl(string fileName)
        {
            try
            {
                var userInfo = await _userManager.GetUserInfo();

                List<EmployeeListOutput> EmployeeFailResult = new List<EmployeeListOutput>();
                List<CheckDateerrOutput> FailResult = new List<CheckDateerrOutput>();
                EmployeeListOutput put = null;
                var filePath = FileVariable.TemporaryFilePath;
                var savePath = filePath + fileName;
                //得到数据
                var excelData = ExcelImportHelper.ToDataTable(savePath);
                var IsExistsdep = 0;
                var IsExistsjobno = 0;
                var IsExistsname = 0;
                var IsExistsbla = 0;
                foreach (var item in excelData.Columns)
                {
                    switch (item.ToString())
                    {
                        case "部门名称":
                            IsExistsdep++;
                            break;
                        case "员工编号":
                            IsExistsjobno++;
                            break;
                        case "姓名":
                            IsExistsname++;
                            break;
                        case "充值期初金额":
                            IsExistsbla++;
                            break;
                        default:

                            break;
                    }
                }
                if (IsExistsdep == 0)
                {
                    FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [部门名称] 列" });
                }
                if (IsExistsjobno == 0)
                {
                    FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [员工编号] 列" });
                }
                if (IsExistsname == 0)
                {
                    FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [姓名] 列" });
                }
                if (IsExistsbla == 0)
                {
                    FailResult.Add(new CheckDateerrOutput() { rowNo = "0", errorMsg = "表格中未找到 [充值期初金额] 列" });
                }
                if (IsExistsdep == 0 || IsExistsjobno == 0 || IsExistsname == 0 || IsExistsbla == 0)
                {
                    return new { dataRow = EmployeeFailResult, errRow = FailResult };
                }
                foreach (var item in excelData.Columns)
                {
                    excelData.Columns[item.ToString()].ColumnName = GetFiledEncoderecbl(item.ToString());
                }
                var _Organizelist = await _db.Queryable<OrganizeEntity>().ToListAsync();
                //卡户
                var dataEmployee = await _baseEmployeeRepository.Where(t => t.DeleteMark == 0 && t.CompanyId == userInfo.companyId).ToListAsync();

                //删除文件
                //FileHelper.DeleteFile(savePath);
                //返回结果
                if (excelData != null && excelData.Rows.Count > 0)
                {
                    var _iserr = 0;
                    var _msg = "";
                    for (int i = 0; i < excelData.Rows.Count; i++)
                    {
                        _iserr = 0;
                        _msg = "";
                        put = new EmployeeListOutput();
                        put.departName = Convert.ToString(excelData.Rows[i]["departName"]);

                        //验证部门
                        var _Organize = _Organizelist.Where(p => p.FullName.Equals(put.departName) && p.CompanyId == userInfo.companyId).ToList();
                        if (_Organize != null && _Organize.Count > 0)
                        {
                            put.departId = _Organize[0].Id;
                            put.departName = _Organize[0].FullName;
                        }
                        else
                        {
                            _msg += "[部门] 系统中不存在;";
                            _iserr++;
                        }
                        put.jobNum = Convert.ToString(excelData.Rows[i]["jobNum"]);
                        var items = dataEmployee.Where(p => p.JobNum.Equals(put.jobNum)).ToList();
                        if (items != null && items.Count > 0)
                        {
                            put.jobNum = Convert.ToString(excelData.Rows[i]["jobNum"]);
                        }
                        else
                        {
                            _msg += "[工号] 系统中不存在;";
                            _iserr++;
                        }
                        put.realName = Convert.ToString(excelData.Rows[i]["realName"]);
                        put.employeeId = dataEmployee.Where(p => p.JobNum.Equals(put.jobNum) && p.RealName.Equals(put.realName)).First().EmployeeId;
                        put.rechargeBalance = Convert.ToDecimal(excelData.Rows[i]["rechargeBalance"]);
                        put.CompanyId = userInfo.companyId;
                        put.CompanyName = userInfo.companyName;

                        if (_iserr > 0)
                        {
                            FailResult.Add(new CheckDateerrOutput()
                            {
                                rowNo = (i + 1).ToString(),
                                errorMsg = _msg
                            });
                        }
                        else
                        {
                            EmployeeFailResult.Add(put);
                        }
                    }
                }
                return new { dataRow = EmployeeFailResult, errRow = FailResult };
            }
            catch (Exception e)
            {

                throw PARKException.Oh(ErrorCode.D1801);
            }
        }
        /// <summary>
        /// 获取字段编码
        /// </summary>
        /// <param name="filed"></param>
        /// <returns></returns>
        private string GetFiledEncoderecbl(string filed)
        {
            switch (filed)
            {
                case "部门名称":
                    return "departName";
                case "员工编号":
                    return "jobNum";
                case "姓名":
                    return "realName";
                case "充值期初金额":
                    return "rechargeBalance";
                default:
                    return "";
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost("Uploaderrecbl")]
        public async Task<dynamic> Uploaderrecbl(IFormFile file)
        {
            return await _fileService.Uploader("", file);
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpPost("InDatarecbl")]
        public async Task<dynamic> InDatarecbl([FromBody] EmpImportDataInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var output = new EmpImportDataOutput();
            string errMsg = string.Empty;
            foreach (var item in input.EmployeeList)
            {
                try
                {
                    var entity = item.Adapt<EmployeeEntity>();
                    errMsg = "";
                    if (string.IsNullOrEmpty(item.jobNum))
                    {
                        errMsg += "工号不能为空;";
                    }
                    if (string.IsNullOrEmpty(item.realName))
                    {
                        errMsg += "姓名不能为空;";
                    }
                    if (errMsg != "")
                    {
                        item.errorMsg = errMsg;
                        output.EmployeeFailResult.Add(item);
                        output.fnum++;
                    }
                    else
                    {
                        output.snum++;
                    }
                }
                catch (Exception ex)
                {
                    item.errorMsg = "发生异常";
                    output.EmployeeFailResult.Add(item);
                    output.fnum++;
                }
            }
            if (output.snum == input.EmployeeList.Count)
            {
                output.resultType = 0;
                //导入成功删除文件
                var filePath = FileVariable.TemporaryFilePath;
                var savePath = filePath + input.fileName;
                FileHelper.DeleteFile(savePath);
                var _Organizelist = await _db.Queryable<OrganizeEntity>().ToListAsync();
                //导入成功写入数据
                foreach (var item in input.EmployeeList)
                {
                    var entity = item.Adapt<EmployeeEntity>();
                    entity.LastModify(entity.EmployeeId);
                    try
                    {
                        //开启事务
                        _db.BeginTran();

                        await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                        //关闭事务
                        _db.CommitTran();
                    }
                    catch (Exception ex)
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1000);
                    }
                }
            }
            else
            {
                output.resultType = -1;
            }
            return output;
        }
        #endregion

        #region 上传图片
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("ImgBasic64UploadAdd")]
        //[AllowAnonymous]
        public async Task<dynamic> ImgBasic64UploadAdd([FromBody] EmployeeCrInput input)
        {
            var _Output = new ImageOutput();
            string strBase64 = input.fileBase64;
            try
            {
                string path = App.Configuration["JNPF_App:SystemPath"];
                var PhotoPath = path + "SystemFile/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                if (!Directory.Exists(PhotoPath))
                {
                    Directory.CreateDirectory(PhotoPath);
                }
                var _FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Guid.NewGuid().ToString().Replace("-", "").Substring(0, 5) + ".jpg";
                string _FilePath = PhotoPath + _FileName;
                string base64img = Regex.Replace(strBase64, "data:image/.*;base64,", "");
                byte[] bytes = Convert.FromBase64String(base64img);
                FileStream fs = new FileStream(_FilePath, FileMode.CreateNew);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
                var _imgUrl = "/Resources/SystemFile/" + DateTime.Now.ToString("yyyyMMdd") + "/" + _FileName;
                //var _imgUrl = "/api/File/Image/annexpic/" + _FileName;
                _Output = new ImageOutput()
                {
                    ret = 1,
                    msg = "上传成功",
                    fileName = _FileName,
                    imgUrl = _imgUrl
                };

                return _Output;
            }
            catch (Exception ex)
            {
                _Output = new ImageOutput()
                {
                    ret = 0,
                    msg = "上传失败"
                };
            }
            return _Output;
        }
        #endregion        

        #region 获取人员
        /// <summary>
        /// 获取人员
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTransferList")]
        public async Task<dynamic> GetTransferList(string departId, string eyeId)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                StringBuilder dbSql = new StringBuilder("select EmployeeId,RealName+'/'+DepartName as RealName from base_employee a where a.F_DeleteMark=0 and a.AccStatus!=3 ");
                dbSql.AppendFormat(" and a.CompanyId='{0}'", userInfo.companyId);
                var data = await _db.SqlQueryable<EmployeeTransferListOutput>(dbSql.ToString()).Select(t => new EmployeeTransferListOutput
                {
                    EmployeeId = t.EmployeeId,
                    RealName = t.RealName
                }).MergeTable().ToListAsync();
                return data;
            }
            else
                return null;
        }
        #endregion

        #region 批量导入卡户，加密手机号，转换卡号
        /// <summary>
        /// 批量导入卡户，加密手机号，转换卡号
        /// </summary>
        /// <returns></returns>
        [HttpPut("EncryEyeMobilePhone")]
        //[NonAction]
        public async Task EncryEyeMobilePhone()
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                StringBuilder dbSql = new StringBuilder("select * from base_employee a where a.F_DeleteMark=0 and a.IsCard=0 ");
                dbSql.AppendFormat(" and a.CompanyId='{0}'", userInfo.companyId);
                var dt = await _db.SqlQueryable<DataTable>(dbSql.ToString()).ToDataTableAsync();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    try
                    {
                        //卡号转
                        var UId = dt.Rows[i]["CardUID"]!=null ? dt.Rows[i]["CardUID"].ToString():"";
                        var CardNo = "";
                        if (!string.IsNullOrEmpty(UId))
                        {
                            string[] _str = new string[4];
                            _str[0] = UId.Substring(6, 2);
                            _str[1] = UId.Substring(4, 2);
                            _str[2] = UId.Substring(2, 2);
                            _str[3] = UId.Substring(0, 2);
                            UId = _str[0] + _str[1] + _str[2] + _str[3];
                            CardNo = Convert.ToInt64(UId, 16).ToString();
                        }
                        //加密手机号
                        var MobilePhone = "";
                        var MobilePhoneSf = "";
                        if (dt.Rows[i]["手机号码"] != null && !string.IsNullOrEmpty(dt.Rows[i]["手机号码"].ToString()) && dt.Rows[i]["手机号码"].ToString().Length == 11)
                        {
                            //处理手机号
                            MobilePhone = Regex.Replace(dt.Rows[i]["手机号码"].ToString(), "(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                            //加密手机号
                            SM4Utils sm4 = new SM4Utils();
                            sm4.secretKey = App.Configuration["DataSafeSettings:phoneNumSecretKey"];
                            sm4.hexString = false;
                            MobilePhoneSf = sm4.Encrypt_ECB(dt.Rows[i]["手机号码"].ToString());
                        }
                        if (!string.IsNullOrEmpty(CardNo) || !string.IsNullOrEmpty(MobilePhone))
                        {
                            StringBuilder sql = new StringBuilder("update base_employee set IsCard=1,");
                            var _str = "";
                            if (!string.IsNullOrEmpty(CardNo))
                            {
                                _str += " CardNo='" + CardNo + "',";
                            }
                            if (!string.IsNullOrEmpty(MobilePhone))
                            {
                                _str += " MobilePhone='" + MobilePhone + "',MobilePhoneSf='" + MobilePhoneSf + "',";
                            }
                            _str = _str.Substring(0, _str.Length - 1);
                            sql.Append(_str);
                            sql.AppendFormat(" where EmployeeId='{0}'", dt.Rows[i]["EmployeeId"].ToString());
                            var Paras = new List<SugarParameter>();
                            var isOk = await _db.Ado.ExecuteCommandAsync(sql.ToString(), Paras);
                        }
                    }
                    catch (Exception ex)
                    {
                        var _msg = ex.Message;
                    }
                }
            }
        }
        #endregion

        /// <summary>
        /// 生成退款单号
        /// </summary>
        /// <param name="mchId"></param>
        /// <returns></returns>
        static string GenerateOutTradeNo(string mchId)
        {
            var ran = new Random();
            return string.Format("{0}{1}{2}", mchId, DateTime.Now.ToString("yyyyMMddHHmmss"), ran.Next(999));
        }

        #region  根据消费卡号获取人员管理
        /// <summary>
        /// 根据消费卡号获取人员管理
        /// </summary>
        /// <param name="companyId">单位Id</param>
        /// <param name="cardNo">卡号</param>
        /// <returns></returns>
        [HttpGet("GetEyeByCardNo")]
        public async Task<dynamic> GetEyeByCardNo(string companyId,string cardNo)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && !string.IsNullOrEmpty(companyId) && !string.IsNullOrEmpty(cardNo))
            {
                var entity = await _db.Queryable<EmployeeEntity>().FirstAsync(p => p.CardNo.Equals(cardNo) && p.CompanyId == companyId);
                var output = entity.Adapt<EmployeeInfoOutput>();
                return output;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 导出消费记录Excel
        /// <summary>
        /// 获取消费记录无分页列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] EmployeeListQuery input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "sortCode" : input.sidx;
                var organizeIds = new List<string>();
                if (!input.organizeId.IsNullOrEmpty())
                    organizeIds = await GetSubOrganizeIds(input.organizeId);
                if (input.departId == "96240625-934F-490B-8AA6-0BC775B18468")
                {
                    input.departId = null;
                }
                //有效期
                List<string> querydate = input.expiryEndDate != null ? input.expiryEndDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startate = querydate != null ? Ext.GetDateTime(querydate.First()) : null;
                DateTime? enddate = querydate != null ? Ext.GetDateTime(querydate.Last()) : null;
                var data = await _db.Queryable<EmployeeEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    .Where(u => u.DeleteMark == 0 && u.AccStatus != 2 && u.AccStatus != 3 && u.AccStatus != 4)
                    //组织机构
                    .WhereIF(organizeIds.Any(), u => organizeIds.Contains(SqlFunc.ToString(u.DepartId)))
                    //关键字查询
                    .WhereIF(!input.keyword.IsNullOrEmpty(), u => u.JobNum.Contains(input.keyword) || u.RealName.Contains(input.keyword) || u.MobilePhone.Contains(input.keyword) || u.CardNo.Contains(input.keyword))
                    //卡户状态
                    .WhereIF(!string.IsNullOrEmpty(input.accStatus), u => u.AccStatus.Equals(input.accStatus))
                    //认证状态
                    .WhereIF(!string.IsNullOrEmpty(input.isauth), u => u.Isauth.Equals(input.isauth))
                    //卡号查询
                    .WhereIF(!string.IsNullOrEmpty(input.cardNo), u => u.CardNo.Contains(input.cardNo) || u.CatCardNo.Contains(input.cardNo))
                    //部门
                    .WhereIF(!string.IsNullOrEmpty(input.departId), p => p.DepartId.Equals(input.departId))
                    //有效期
                    .WhereIF(querydate != null, u => u.ExpiryEndDate >= new DateTime(startate.ToDate().Year, startate.ToDate().Month, startate.ToDate().Day, 0, 0, 0))
                    .WhereIF(querydate != null, u => u.ExpiryEndDate <= new DateTime(enddate.ToDate().Year, enddate.ToDate().Month, enddate.ToDate().Day, 23, 59, 59))
                    //员工类型
                    .WhereIF(!string.IsNullOrEmpty(input.employeType), p => p.EmployeType.Equals(input.employeType))
                    //卡片类型
                    .WhereIF(!string.IsNullOrEmpty(input.cardTypeId), p => p.CardTypeId.Equals(input.cardTypeId))
                    //超期状态
                    .WhereIF(!string.IsNullOrEmpty(input.overdueStatus), u => u.OverdueStatus.Equals(input.overdueStatus))
                    .Select(it => new EmployeeListOutput
                    {
                        employeeId = it.EmployeeId,
                        jobNum = it.JobNum,
                        realName = it.RealName,
                        gender = it.Gender,
                        employeType = it.EmployeType,
                        departId = it.DepartId,
                        departName = it.DepartName,
                        headIcon = it.HeadIcon,
                        mobilePhone = it.MobilePhone,
                        isCard = it.IsCard,
                        cardNo = it.CardNo,
                        catCardNo = it.CatCardNo, //长安通卡号
                        expiryEndDate = it.ExpiryEndDate,
                        welfareBalance = it.WelfareBalance,
                        rechargeBalance = it.RechargeBalance,
                        accStatus = it.AccStatus,
                        isauth = it.Isauth,
                        description = it.Description,
                        CreatorTime = it.CreatorTime,
                        cardUID = it.CardUID,
                        cardTypeId = it.CardTypeId,
                        cardTypeName = it.CardTypeName,
                        overdueStatus = it.OverdueStatus,
                        eyejob = it.Eyejob,
                        sortCode = it.SortCode
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToListAsync();
                return data;
            }
            else
                return null;
        }
        /// <summary>
        /// 导出记录
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] EmployeeListQuery input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<EmployeeListOutput>();
            var exportDataNew = new List<EmployeeListOutput>();
            var entity = input.Adapt<ConsumRechargeEntity>();
            if (input.dataType == 0)
            {
                var data = Clay.Object(await this.GetList(input));
                exportData = data.Solidify<PageResult<EmployeeListOutput>>().list;
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }
            foreach (EmployeeListOutput item in exportData)
            {
                if (item.gender == 1)
                {
                    item.genderName = "男";
                }
                else
                {
                    item.genderName = "女";
                }
                if (item.isauth == 1)
                {
                    item.isauthName = "已认证";
                }
                else
                {
                    item.isauthName = "未认证";
                }
                switch (item.accStatus)
                {
                    case 0:
                        item.accStatusName = "已禁用";
                        break;
                    case 1:
                        item.accStatusName= "正常";
                        break;
                    case 2:
                        item.accStatusName = "已冻结";
                        break;
                    case 3:
                        item.accStatusName = "已挂失";
                        break;
                    case 4:
                        item.accStatusName = "已销户";
                        break;
                }
                item.expiryEndDateEx = item.expiryEndDate!=null? Convert.ToDateTime(item.expiryEndDate).ToString("yyyy-MM-dd"):"";
                exportDataNew.Add(item);
            }
            List<ParamsModel> paramList = "[{\"value\":\"工号\",\"field\":\"jobNum\"},{\"value\":\"姓名\",\"field\":\"realName\"},{\"value\":\"性别\",\"field\":\"genderName\"},{\"value\":\"卡面卡号\",\"field\":\"catCardNo\"},{\"value\":\"手机号\",\"field\":\"mobilePhone\"},{\"value\":\"部门\",\"field\":\"departName\"},{\"value\":\"职位\",\"field\":\"eyejob\"},{\"value\":\"卡片类型\",\"field\":\"cardTypeName\"},{\"value\":\"卡有效期\",\"field\":\"expiryEndDateEx\"},{\"value\":\"账户余额\",\"field\":\"rechargeBalance\"},{\"value\":\"认证状态\",\"field\":\"isauthName\"},{\"value\":\"账户状态\",\"field\":\"accStatusName\"},{\"value\":\"备注\",\"field\":\"description\"},]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = userInfo.companyName + "_" + "人员卡户_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<EmployeeListOutput>.Export(exportDataNew, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "api/file/Download?encryption=" + DESCEncryption.Encrypt(fileName, "JNPF")
            };
            return output;
        }
        #endregion

        #region 批量生成虚拟卡号
        /// <summary>
        /// 批量生成虚拟卡号
        /// </summary>
        /// <returns></returns>
        [HttpPut("EncryEyeCardNo")]
        //[NonAction]
        public async Task EncryEyeCardNo()
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                StringBuilder dbSql = new StringBuilder("select * from base_employee a where a.F_DeleteMark=0");
                dbSql.AppendFormat(" and a.CompanyId='{0}'", userInfo.companyId);
                var dt = await _db.SqlQueryable<DataTable>(dbSql.ToString()).ToDataTableAsync();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    try
                    {
                        var Paras = new List<SugarParameter>();
                        Paras.Add(new SugarParameter("@v_CardNo", null, true));
                        _db.Ado.UseStoredProcedure().ExecuteCommand("P_Public_AutoCreateCardNo", Paras);
                        object _obj = Paras[0].Value;
                        if (_obj != null)
                        {
                            //生成卡号
                            var CardNo = _obj.ToString();
                            if (!string.IsNullOrEmpty(CardNo))
                            {
                                StringBuilder sql = new StringBuilder("update base_employee set IsCard=1,");
                                sql.AppendFormat(" CardNo='{0}',", CardNo);
                                sql.AppendFormat(" CatCardNo='{0}' ", CardNo);
                                sql.AppendFormat(" where EmployeeId='{0}'", dt.Rows[i]["EmployeeId"].ToString());                                
                                await _db.Ado.ExecuteCommandAsync(sql.ToString(), Paras);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var _msg = ex.Message;
                    }
                }
            }
        }
        #endregion

        #region 批量删除宇泛空置人员
        /// <summary>
        /// 批量删除宇泛空置人员
        /// </summary>
        /// <returns></returns>
        [HttpPut("DeleteAdmitGuids")]
        public async Task DeleteAdmitGuids()
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var Paras = new List<SugarParameter>();
                //调用宇泛接口
                var _appInfo = _parkCacheRepository.GetCacheUniubiAppInfo(userInfo.companyId);
                if (_appInfo != null && _appInfo.uni_is > 0)
                {
                    StringBuilder dbSql = new StringBuilder("select * from base_employee_AdmitGuid a where ");
                    dbSql.AppendFormat(" a.CompanyId='{0}'", userInfo.companyId);
                    var dt = await _db.SqlQueryable<DataTable>(dbSql.ToString()).ToDataTableAsync();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        try
                        {
                            var _admitGuid = dt.Rows[i]["AdmitGuid"].ToString();
                            //调用宇泛接口
                            var dpfout = _uniubiSdkRepository.eyeDelete(_admitGuid , userInfo.companyId);
                            StringBuilder sql = new StringBuilder("update base_employee_AdmitGuid set IsAnt=1,");                         
                            sql.AppendFormat(" retMsg='{0}' ", dpfout.ToJson());
                            sql.AppendFormat(" where Id='{0}'", dt.Rows[i]["Id"].ToString());
                            await _db.Ado.ExecuteCommandAsync(sql.ToString(), Paras);
                        }
                        catch (Exception ex)
                        {
                            var _msg = ex.Message;
                        }
                    }
                }  
            }
        }
        #endregion
    }
}
